package com.itboye.jinpuyiyuan.fragment;


import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.activity.home.BranchSelectActivity;
import com.itboye.jinpuyiyuan.activity.home.finddoctor.DoctorDetailActivity;
import com.itboye.jinpuyiyuan.activity.home.finddoctor.FindDoctorActivity;
import com.itboye.jinpuyiyuan.activity.home.healthconsultation.HealthConsultationActivity;
import com.itboye.jinpuyiyuan.activity.home.healthconsultation.HealthConsultationDetailActivity;
import com.itboye.jinpuyiyuan.activity.home.hospitalserver.HospitalServerActivity;
import com.itboye.jinpuyiyuan.activity.home.register.RegisterActivity;
import com.itboye.jinpuyiyuan.activity.home.testserver.TestServerActivity;
import com.itboye.jinpuyiyuan.activity.login.LoginOrRegisterActivity;
import com.itboye.jinpuyiyuan.activity.message.NotificationInfoActivity;
import com.itboye.jinpuyiyuan.adapter.FindDoctorArrayAdapter;
import com.itboye.jinpuyiyuan.adapter.HealthConsultationAdapter;
import com.itboye.jinpuyiyuan.adapter.RegisterDoctorDetailAdapter;
import com.itboye.jinpuyiyuan.base.BaseFragment;
import com.itboye.jinpuyiyuan.bean.ArticleListBean;
import com.itboye.jinpuyiyuan.bean.BannerBean;
import com.itboye.jinpuyiyuan.bean.BranchBean;
import com.itboye.jinpuyiyuan.bean.ConfigBean;
import com.itboye.jinpuyiyuan.bean.NoticeBean;
import com.itboye.jinpuyiyuan.bean.QueryDoctorListBean;
import com.itboye.jinpuyiyuan.bean.QueryDoctorListBeanNew;
import com.itboye.jinpuyiyuan.presenter.BranchAddressPresenter;
import com.itboye.jinpuyiyuan.utils.BasePtr;
import com.itboye.jinpuyiyuan.utils.LocationUtils;
import com.itboye.jinpuyiyuan.utils.MarqueeTextViewClickListener;
import com.itboye.jinpuyiyuan.utils.MyRollViewPager;
import com.itboye.jinpuyiyuan.utils.PtrHTFrameLayout;
import com.itboye.jinpuyiyuan.utils.logincontroller.LoginController;
import com.itboye.jinpuyiyuan.utils.logincontroller.UnLoginState;
import com.itboye.jinpuyiyuan.utils.sputil.Const;
import com.itboye.jinpuyiyuan.utils.sputil.SPUtils;
import com.itboye.jinpuyiyuan.utils.volley.ResultEntity;
import com.itboye.jinpuyiyuan.widget.IsStringSPUtils;
import com.itboye.jinpuyiyuan.widget.MarqueeTextView;
import com.itboye.jinpuyiyuan.widget.MyListView;
import com.itboye.jinpuyiyuan.widget.loadingutil.MAlert;
import com.jude.rollviewpager.OnItemClickListener;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.adapter.LoopPagerAdapter;
import com.jude.rollviewpager.hintview.IconHintView;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.Timer;
import java.util.TimerTask;

import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;


/**
 * 首页
 */
public class HomeFragment extends BaseFragment implements Observer {
    //title
    private ImageView leftImg, rightImg;
    private TextView leftTv, tvTitle;
    private RelativeLayout rlLeft;


    private LinearLayout registerLL, findDoctorLL, hospitalServerLL, testServerLL, healthConsultLL, famousDoctorLL;
    private ImageView registerImg, findDoctorImg, hospitalServerImg, testServerImg;
    private TextView noticeTv,registerTv, findDoctorTv, hospitalServerTv, testServerTv;
    private ImageView healthConsultTvMore, famousDoctorMoreTv;
    private BranchAddressPresenter presenter;
    private MyRollViewPager rollVp;
    private TestLoopAdapter mLoopAdapter;
    private String [] imgs;
    private List<BannerBean> list;
    private String uid;
    private MarqueeTextView marqueeTv;
    private ListView noticeLv;
    private String [] arrayList;
    private List<NoticeBean> noticeList;
    private MyListView famousDoctorList,healthList;
//    private RelativeLayout doctorRL,healthRL;
    private PtrHTFrameLayout commend_anchor_ptr;
    //金普名医
    private RegisterDoctorDetailAdapter registerDoctorDetailAdapter;
    private ArrayList<QueryDoctorListBeanNew.DoctorItem> arrDoctor;
    //文章咨询
    private ArrayList<ArticleListBean> arrArticle;

    private HealthConsultationAdapter healthConsultationAdapter;

    private String hosId;
    @Override
    public int initView() {
        return R.layout.fragment_home;

    }

    @Override
    public void onMyActivityCreated() {
        tvTitle.setText("金普医生");
        rightImg.setVisibility(View.GONE);
        //左右滑动时刷新控件禁止掉
        commend_anchor_ptr.disableWhenHorizontalMove(true);
        leftImg.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.dingwei_new));
        leftTv.setVisibility(View.VISIBLE);
        list=new ArrayList<>();
        arrDoctor=new ArrayList<>();
        arrArticle=new ArrayList<>();

        uid= (String) SPUtils.get(getActivity().getApplication(),null, Const.UID,"");
        presenter = new BranchAddressPresenter(this);


        //分院查询
        String lngAndLatWithNetwork = new LocationUtils().getLngAndLat(getActivity());
        presenter.queryBranch(lngAndLatWithNetwork.split(",")[0],lngAndLatWithNetwork.split(",")[1]);//分院查询
        //查询配置
        presenter.getConfig();
        //查询公告  查询消息接口  公告: 00P006001;通知: 00P006002,私聊: 00P006003
        if (uid.equals("")||uid==null){
            //去登录
        }else {
            presenter.queryMessage(uid,"00P006001",1,10);

        }
        //查询轮播
        presenter.queryBanner("00P007001");
        //查询资讯
        presenter.queryArticle("00P003004","","published",1,10);//查询文章
        initRefresh();

        //金普医院
        registerDoctorDetailAdapter=new RegisterDoctorDetailAdapter(getActivity(),arrDoctor);
        famousDoctorList.setAdapter(registerDoctorDetailAdapter);
        famousDoctorList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), DoctorDetailActivity.class);

                intent.putExtra("doctorId",arrDoctor.get(position).getUid()+"");
                intent.putExtra("doctorName",arrDoctor.get(position).getNickname());
                startActivity(intent);
            }
        });
        //健康咨询
        healthConsultationAdapter=new HealthConsultationAdapter(getActivity(),arrArticle);
        healthList.setAdapter(healthConsultationAdapter);
        healthList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), HealthConsultationDetailActivity.class);
                intent.putExtra("articleId",arrArticle.get(position).getId());
                intent.putExtra("islike",arrArticle.get(position).getIs_like());
                startActivity(intent);
            }
        });
//        presenter2=new BranchAddressPresenter(this);
//        //类型  通知00P006002 公告 00P006001
//        presenter2.queryMessage(uid,"00P006001",1,10);
        rollVp.setPlayDelay(1600);
        rollVp.setAdapter(mLoopAdapter = new TestLoopAdapter(rollVp));

        rollVp.setHintView(new IconHintView(getActivity(),R.drawable.focus,R.drawable.normal,35));
        rollVp.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
//                app跳转web原生
                if (list.get(position).getUrl()==null){
                    return;
                }
                if (!list.get(position).getUrl().equals("")){
                    Intent intent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse(list.get(position).getUrl()));
                    startActivity(intent);
                }

            }
        });

    }

    private void initRefresh() {
        BasePtr.setRefreshOnlyStyle(commend_anchor_ptr);
        commend_anchor_ptr.autoRefresh();
        commend_anchor_ptr.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {

            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //查询公告  查询消息接口  公告: 00P006001;通知: 00P006002,私聊: 00P006003
                if (uid==null||uid.equals("")){
                    //没登陆
                }else {
                    presenter.queryMessage(uid,"00P006001",1,10);

                }
                //查询轮播
                presenter.queryBanner("00P007001");
                //查询资讯
                presenter.queryArticle("00P003004","","published",1,10);//查询文章
            }
        });
    }

    //设置刷新


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.leftImg:
            case R.id.leftTv:
            case R.id.rlLeft:
                if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                    LoginController.setLoginState(new UnLoginState());
                    startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
                }else {
                    startActivityForResult(new Intent(getActivity(), BranchSelectActivity.class), 120);
                }
                break;

            //挂号
            case R.id.registerLL:
                if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                    LoginController.setLoginState(new UnLoginState());
                    startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
                }else {
//                    MAlert.alert("待开发");
                    startActivity(new Intent(getActivity(), RegisterActivity.class));
                }
                break;
            //找医生
            case R.id.findDoctorLL:
                if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                    LoginController.setLoginState(new UnLoginState());
                    startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
                }else {
                    startActivity(new Intent(getActivity(), FindDoctorActivity.class));
                }
                break;

            //住院服务
            case R.id.hospitalServerLL:
                if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                    LoginController.setLoginState(new UnLoginState());
                    startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
                }else {
//                    MAlert.alert("待开发");

                    startActivity(new Intent(getActivity(), HospitalServerActivity.class));
                }
                break;

            //体检服务
            case R.id.testServerLL:
                if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                    LoginController.setLoginState(new UnLoginState());
                    startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
                }else {
//                    MAlert.alert("待开发");

                    startActivity(new Intent(getActivity(), TestServerActivity.class));
                }
                break;
            //健康咨询
            case R.id.healthConsultLL:
            case R.id.healthConsultTvMore:
                if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                    LoginController.setLoginState(new UnLoginState());
                    startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
                }else {
                    startActivity(new Intent(getActivity(), HealthConsultationActivity.class));
                }
                break;
            //金普名医
            case R.id.famousDoctorLL:
            case R.id.famousDoctorMoreTv:
                if (IsStringSPUtils.IsUid()==null||IsStringSPUtils.IsUid().equals("")){
                    LoginController.setLoginState(new UnLoginState());
                    startActivity(new Intent(getActivity(),LoginOrRegisterActivity.class));
                }else {
                    startActivity(new Intent(getActivity(), FindDoctorActivity.class));
                }
                break;
//
//            case R.id.healthRL:
//                startActivity(new Intent(getActivity(),HealthConsultationDetailActivity.class));
//
//                break;
//            case R.id.doctorRL:
//
//
//                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 120 && resultCode == 121) {
            leftTv.setText(data.getStringExtra("hospitalName"));
            hosId=data.getStringExtra("hosid");
            presenter.queryDoctor(hosId,"","","","","");
        }
    }

    @Override
    public void update(Observable observable, Object o) {
        ResultEntity entity = handlerError(o);

        if (entity != null) {
            if (entity.getEventType() == BranchAddressPresenter.config_success) {
                ConfigBean date = (ConfigBean) entity.getData();
                SPUtils.put(getActivity(),null,"version",date.getAndroid_version());
                SPUtils.put(getActivity(),null,"limit",Integer.parseInt(date.getId_card_modify_limit()));

//                Toast.makeText(getActivity(), date.getAndroid_version(), Toast.LENGTH_LONG).show();

            } else if (entity.getEventType() == BranchAddressPresenter.config_fail) {

//                MAlert.alert(entity.getMsg());
            }else if(entity.getEventType()==BranchAddressPresenter.By_Banners_query_success){
//                MAlert.alert(entity.getMsg());
                list= (List<BannerBean>) entity.getData();

                if (list.size()>0){
                    imgs=new String [list.size()];
                    for (int i=0;i<list.size();i++){
                     imgs[i]=list.get(i).getImg();
                    }
                    mLoopAdapter.setImgs(imgs);
                }

            }else if (entity.getEventType()== BranchAddressPresenter.By_Banners_query_fail){
                MAlert.alert(entity.getMsg());
            } else if (entity.getEventType()==BranchAddressPresenter.By_HospDoct_query_success){
//                MAlert.alert("查询医师成功");
                if (arrDoctor.size()>0){
                    arrDoctor.clear();
                }
                QueryDoctorListBeanNew queryDoctorListBean= (QueryDoctorListBeanNew) entity.getData();
                if (queryDoctorListBean.getList().size()>0){
                    for (int i=0;i<queryDoctorListBean.getList().size();i++){
                        if (!queryDoctorListBean.getList().get(i).getDept_id().equals("")&&!queryDoctorListBean.getList().get(i).getAlibaichuan_id().equals("")){
                            arrDoctor.add(queryDoctorListBean.getList().get(i));
                        }
                        if (arrDoctor.size()>1){
                            registerDoctorDetailAdapter.addData(arrDoctor);
                            return;
                        }
                    }
//                    arrDoctor.add(queryDoctorListBean.getList().get(0));
//                    arrDoctor.add(queryDoctorListBean.getList().get(1));
                }
                registerDoctorDetailAdapter.addData(arrDoctor);
            }else if (entity.getEventType()==BranchAddressPresenter.By_HospDoct_query_fail){

//                MAlert.alert("查询医师失败");
            } else  if (entity.getEventType()== BranchAddressPresenter.By_Post_queryByCateOrTag_success){
                List<ArticleListBean> listBeans= (List<ArticleListBean>) entity.getData();

                if (listBeans.get(0).getCategory().equals("00P003003")){//系统公告


                }else {//资讯
                    if (arrArticle.size()>0){
                        arrArticle.clear();
                    }
                    if (listBeans.size()>2){
                        arrArticle.add(listBeans.get(0));
                        arrArticle.add(listBeans.get(1));
                    }else {
                        arrArticle.addAll(listBeans);
                    }
                    healthConsultationAdapter.addData(arrArticle);
                }


            }else if (entity.getEventType()== BranchAddressPresenter.By_Post_queryByCateOrTag_fail){
//                MAlert.alert(entity.getMsg());
            }else if (entity.getEventType() == BranchAddressPresenter.queryAddress_success) {
//                MAlert.alert("请求成功");
                BranchBean bean = (BranchBean) entity.getData();

                if (bean.getList().size()>0){
                    leftTv.setText(bean.getList().get(0).getName());
                    hosId=bean.getList().get(0).getId()+"";
                    presenter.queryDoctor(hosId,"","","","","");
                }
            } else if (entity.getEventType() == BranchAddressPresenter.queryAddress_fail) {
//                MAlert.alert(entity.getMsg(), Gravity.TOP);
            }else if (entity.getEventType()== BranchAddressPresenter.By_Message_query_success){
              List<NoticeBean>  message= (List<NoticeBean>) entity.getData();

                //添加公告数据
                arrayList=new String[message.size()];
                for (int i=0;i<message.size();i++){
                    arrayList[i]=message.get(i).getTitle();
                }
                marqueeTv.setTextArraysAndClickListener(arrayList,message, new MarqueeTextViewClickListener() {
                    @Override
                    public void onClick(View view) {

//              MAlert.alert("点上公告栏了");
                    }
                });
                Log.d("===listnotice",list.size()+"");

            }else if (entity.getEventType()== BranchAddressPresenter.By_Message_query_fail){
//                MAlert.alert("获取公告列表失败");

            }

        }
        commend_anchor_ptr.refreshComplete();
    }

    private class TestLoopAdapter extends LoopPagerAdapter {
        String[] imgs = new String[0];

        public void setImgs(String[] imgs){
            this.imgs = imgs;
            notifyDataSetChanged();
        }


        public TestLoopAdapter(RollPagerView viewPager) {
            super(viewPager);
        }

        @Override
        public View getView(ViewGroup container, int position) {
            Log.i("RollViewPager","getView:"+imgs[position]);

            ImageView view = new ImageView(container.getContext());
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.i("RollViewPager","onClick");
                }
            });
            view.setScaleType(ImageView.ScaleType.CENTER_CROP);
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            Glide.with(getActivity())
                    .load(imgs[position])
                    .placeholder(R.drawable.defeat_lunbo)
                    .into(view);
            return view;
        }

        @Override
        public int getRealCount() {
            return imgs.length;
        }

    }


}
